package flux;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import article.ArticleHTML;
import article.ArticleTXT;
import article.ArticleXML;

public class FluxURL extends Flux{
	
	public FluxURL(String urlFlux) {
		super(urlFlux);
		this.recupererUrlType();
		
	}

	public void recupererUrlType(){
		if(this.isHTML(this.getUrlFlux())){
			this.creeArticlesHTML();
		}
		else if(this.isXML(this.getUrlFlux())){
			this.creeArticlesXML();
		}
		/*else if(this.isMarkdown(listFichier[i])){
			//this.getListArticles().add(new ArticleHTML());
		}*/
	}
	
	public void creeArticlesHTML(){
		try {
			boolean start = false, stop = false;
			URL url = new URL(this.getUrlFlux());
	        URLConnection yc = url.openConnection();
	        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
	        String inputLine;
	        String chaine="";
	        while ((inputLine = in.readLine()) != null) {
	        	if(inputLine.contains("<article")){
	        		start = true; stop = false;
	        	}
	        	else if(inputLine.contains("</article")){
	        		start=false; stop=true;
	        		chaine += inputLine;
	        		this.getListArticles().add(new ArticleHTML(chaine));
	        		chaine = "";
	        	}
	        	if(start && !stop){
	        		chaine += inputLine+"\n";
	        	}
	        }
	        in.close();
		}
		catch(Exception e){e.printStackTrace();}
	}

	public void creeArticlesXML(){
		try {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            URL url = new URL(this.getUrlFlux());
            Document doc = builder.parse(url.openStream());
            NodeList nodes = null;
            nodes = doc.getElementsByTagName("item");
            for (int i = 0; i < nodes.getLength(); i++) {
            	this.getListArticles().add(new ArticleXML(nodes.item(i)));
            }
		}
		catch(Exception e){e.printStackTrace();}
		
	}
	

	public boolean isHTML(String fichier){
		String[] chaine = fichier.split("[.]");
		if(chaine[chaine.length-1].equals("html") || chaine[chaine.length-1].equals("com") || chaine[chaine.length-1].equals("com/")
		|| chaine[chaine.length-1].equals("fr") || chaine[chaine.length-1].equals("fr/")){
			return true;
		}
		return false;
	}
	
	public boolean isXML(String fichier){
		String[] chaine = fichier.split("[.]");
		if(chaine[chaine.length-1].equals("xml")){
			return true;
		}
		return false;
	}
}
